var constant = require('../../const');
var models = require('../../models');
var AV = require('leanengine');


//获取待审核记录
function getWaitingView(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
  var query = new AV.Query(models.MLInfoChangeNotify);
  query.equalTo("status",0);
  query.include("user");
  query.limit(1000);
  query.descending("createdAt"); 
  query.find({
    success:function(notifys) {
      var data = { "username": req.session.username, "notifys": notifys};
      res.render('admin/mistake/waitingView', data);
    },
    error: function(error) {
      res.render('admin/mistake/waitingView', {"username": req.session.username});
    }
  });
}

//忽略记录
function passview(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
  var notifyId = req.body.notifyId;

  var query = new AV.Query(models.MLInfoChangeNotify);
  query.get(notifyId, {
    success:function(notify) {
    	notify.set("status",2);
    	notify.save({
        success: function() {
          res.send({"code":0,"msg":"忽略失败"});
        },
        error: function(error) {
          res.send({"code":1,"msg":"忽略失败"});
        }
      });      
    },
    error: function(error) {
      res.send({"code":1,"msg":"忽略失败"});
    }
  });
}

//警告并回复
function alertReply(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
  var notifyId = req.body.notifyId;
  var content = req.body.content||"";
  var query = new AV.Query(models.MLInfoChangeNotify);
  query.include("user");
  query.get(notifyId, {
    success:function(notify) {
    	var user = notify.get("user");
    	user.set("status",constant.USER_STATUS_BADINFO);
    	user.save().then(function(user){
    		var tokenQuery = new AV.Query(models.HXToken);
        tokenQuery.descending("createdAt");

          tokenQuery.find({
            success:function(results){
              var token = results[0].get('token');
              // 发送会话消息
              AV.Cloud.httpRequest({
                method: 'POST',
                url: 'https://a1.easemob.com/xiaocan/'+constant.APP_NAME+'/messages',
                headers: {
                  "Content-Type":"application/json",
                  "Authorization":"Bearer "+token
                },
                body:{
                  "target_type" : "users", // users 给用户发消息, chatgroups 给群发消息
                  "target" : [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
                                               // 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
                                               // 数组元素是groupid
                  "msg" : {
                    "type":"cmd",
                    "action" : constant.ACTION_RESET_USER
                    },
                  "from" : "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
                },
                success: function(httpResponse) {
                  AV.Cloud.run('sendSysMsg', {"touserId":user.id,"msg": content}, {
                    success: function(result) {
                        res.send({"code":0,"msg":"发送成功"});
                      },
                      error: function(error) {
                        res.send({"code":1,"msg":"发送失败"});
                      }
                  });
                  //保存notify
                  notify.set("status",2);
    							notify.save()
                },
                error: function(httpResponse) {
                  res.send({"code":1,"msg":"发送失败"});          
                }
              });
            },
            error: function(error) {
              res.send({"code":1,"msg":"请求失败"});
            }
        })        
    	})     
    },
    error: function(error) {
      res.send({"code":1,"msg":"失败"});
    }
  });
}

function alertReplyById(req,res){
  if (!req.AV.user) {
    res.redirect('/admin');
  }
  var userId = req.body.userId;
  var content = req.body.content||"";
  var query = new AV.Query(models.MLUser);
  query.get(userId, {
    success:function(user) {
      user.set("status",constant.USER_STATUS_BADINFO);
      user.save().then(function(user){
        var tokenQuery = new AV.Query(models.HXToken);
        tokenQuery.descending("createdAt");

          tokenQuery.find({
            success:function(results){
              var token = results[0].get('token');
              // 发送会话消息
              AV.Cloud.httpRequest({
                method: 'POST',
                url: 'https://a1.easemob.com/xiaocan/'+constant.APP_NAME+'/messages',
                headers: {
                  "Content-Type":"application/json",
                  "Authorization":"Bearer "+token
                },
                body:{
                  "target_type" : "users", // users 给用户发消息, chatgroups 给群发消息
                  "target" : [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
                                               // 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
                                               // 数组元素是groupid
                  "msg" : {
                    "type":"cmd",
                    "action" : constant.ACTION_RESET_USER
                    },
                  "from" : "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
                },
                success: function(httpResponse) {
                  AV.Cloud.run('sendSysMsg', {"touserId":user.id,"msg": content}, {
                    success: function(result) {
                        res.send({"code":0,"msg":"发送成功"});
                      },
                      error: function(error) {
                        res.send({"code":1,"msg":"发送失败"});
                      }
                  });
                  //保存notify
                  notify.set("status",2);
                  notify.save()
                },
                error: function(httpResponse) {
                  res.send({"code":1,"msg":"发送失败"});          
                }
              });
            },
            error: function(error) {
              res.send({"code":1,"msg":"请求失败"});
            }
        })        
      })     
    },
    error: function(error) {
      res.send({"code":1,"msg":"失败"});
    }
  });
}

//获取复审记录
function getReView(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
  var query = new AV.Query(models.MLInfoChangeNotify);
  query.equalTo("status",1);
  query.include("user");
  query.limit(1000);
  query.descending("createdAt"); 
  query.find({
    success:function(notifys) {
      var data = { "username": req.session.username, "notifys": notifys};
      res.render('admin/mistake/reView', data);
    },
    error: function(error) {
      res.render('admin/mistake/reView', {"username": req.session.username});
    }
  });
}

//封禁账号
function disableUser(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
	var notifyId = req.body.notifyId;
	var query = new AV.Query(models.MLInfoChangeNotify);
	query.include("user");
  query.get(notifyId).then(function(notify){
  		var user = notify.get("user");            
      user.set("status", constant.USER_STATUS_DISABLE)
      user.save(null,{
        success: function(user) { 
          var tokenQuery = new AV.Query(models.HXToken);
              tokenQuery.descending("createdAt");
          tokenQuery.find({
            success:function(results){
              var token = results[0].get('token');
              // 发送会话消息
              AV.Cloud.httpRequest({
                method: 'POST',
                url: 'https://a1.easemob.com/xiaocan/'+constant.APP_NAME+'/messages',
                headers: {
                  "Content-Type":"application/json",
                  "Authorization":"Bearer "+token
                },
                body:{
                  "target_type" : "users", // users 给用户发消息, chatgroups 给群发消息
                  "target" : [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
                                               // 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
                                               // 数组元素是groupid
                  "msg" : {
                    "type":"cmd",
                    "action" : constant.ACTION_DISABLE_USER
                    },
                  "from" : "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的
                  
                },
                success: function(httpResponse) {
                	//保存notify
                  notify.set("status",2);
    							notify.save()
                  res.send({"code":0,"msg":"封号成功"});
                },
                error: function(httpResponse) {
                  res.send({"code":1,"msg":"封号失败"});          
                }
              });
            },
            error:function(){
              res.send({"code":1,"msg":"封号失败"});
            }
          })             
          
        },
        error: function(error) {
          res.send({"code":1,"msg":"封号失败"});
        }
      })
    });
}

function disableUserWithId(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
	var userId = req.body.userId;
	var query = new AV.Query(models.MLUser);
  query.get(userId).then(function(user){            
      user.set("status", constant.USER_STATUS_DISABLE)
      user.save(null,{
        success: function(user) { 
          var tokenQuery = new AV.Query(models.HXToken);
              tokenQuery.descending("createdAt");
          tokenQuery.find({
            success:function(results){
              var token = results[0].get('token');
              // 发送会话消息
              AV.Cloud.httpRequest({
                method: 'POST',
                url: 'https://a1.easemob.com/xiaocan/'+constant.APP_NAME+'/messages',
                headers: {
                  "Content-Type":"application/json",
                  "Authorization":"Bearer "+token
                },
                body:{
                  "target_type" : "users", // users 给用户发消息, chatgroups 给群发消息
                  "target" : [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
                                               // 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
                                               // 数组元素是groupid
                  "msg" : {
                    "type":"cmd",
                    "action" : constant.ACTION_DISABLE_USER
                    },
                  "from" : "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的
                  
                },
                success: function(httpResponse) {
                
                  res.send({"code":0,"msg":"封号成功"});
                },
                error: function(httpResponse) {
                  res.send({"code":1,"msg":"封号失败"});          
                }
              });
            },
            error:function(){
              res.send({"code":1,"msg":"封号失败"});
            }
          })             
          
        },
        error: function(error) {
          res.send({"code":1,"msg":"封号失败"});
        }
      })
    });
}

//回复正常状态
function resumeUser(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
  var notifyId = req.body.notifyId;
  var query = new AV.Query(models.MLInfoChangeNotify);
  query.include("user");
  query.get(notifyId, {
    success:function(notify) {
    	var user = notify.get("user");
    	user.set("status",constant.USER_STATUS_NORMAL);
    	user.save().then(function(user){
    		var tokenQuery = new AV.Query(models.HXToken);
        tokenQuery.descending("createdAt");

          tokenQuery.find({
            success:function(results){
              var token = results[0].get('token');
              // 发送会话消息
              AV.Cloud.httpRequest({
                method: 'POST',
                url: 'https://a1.easemob.com/xiaocan/'+constant.APP_NAME+'/messages',
                headers: {
                  "Content-Type":"application/json",
                  "Authorization":"Bearer "+token
                },
                body:{
                  "target_type" : "users", // users 给用户发消息, chatgroups 给群发消息
                  "target" : [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
                                               // 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
                                               // 数组元素是groupid
                  "msg" : {
                    "type":"cmd",
                    "action" : constant.ACTION_RESET_USER
                    },
                  "from" : "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
                },
                success: function(httpResponse) {
                  AV.Cloud.run('sendSysMsg', {"touserId":user.id,"msg": "您的资料审核通过，您的身份已经恢复"}, {
                    success: function(result) {
                        res.send({"code":0,"msg":"发送成功"});
                      },
                      error: function(error) {
                        res.send({"code":1,"msg":"发送失败"});
                      }
                  });
                  	//保存notify
                  notify.set("status",2);
    							notify.save()
                },
                error: function(httpResponse) {
                  res.send({"code":1,"msg":"发送失败"});          
                }
              });
            },
            error: function(error) {
              res.send({"code":1,"msg":"请求失败"});
            }
        })        
    	})     
    },
    error: function(error) {
      res.send({"code":1,"msg":"失败"});
    }
  });
}

function resumeUserWithId(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
  var userId = req.body.userId;
  var query = new AV.Query(models.MLUser);
  query.get(userId, {
    success:function(user) {
    	user.set("status",constant.USER_STATUS_NORMAL);
    	user.save().then(function(user){
    		var tokenQuery = new AV.Query(models.HXToken);
        tokenQuery.descending("createdAt");

          tokenQuery.find({
            success:function(results){
              var token = results[0].get('token');
              // 发送会话消息
              AV.Cloud.httpRequest({
                method: 'POST',
                url: 'https://a1.easemob.com/xiaocan/'+constant.APP_NAME+'/messages',
                headers: {
                  "Content-Type":"application/json",
                  "Authorization":"Bearer "+token
                },
                body:{
                  "target_type" : "users", // users 给用户发消息, chatgroups 给群发消息
                  "target" : [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
                                               // 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
                                               // 数组元素是groupid
                  "msg" : {
                    "type":"cmd",
                    "action" : constant.ACTION_RESET_USER
                    },
                  "from" : "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
                },
                success: function(httpResponse) {
                  AV.Cloud.run('sendSysMsg', {"touserId":user.id,"msg": "您的资料审核通过，您的身份已经恢复为口袋恋人了"}, {
                    success: function(result) {
                        res.send({"code":0,"msg":"发送成功"});
                      },
                      error: function(error) {
                        res.send({"code":1,"msg":"发送失败"});
                      }
                  });
                },
                error: function(httpResponse) {
                  res.send({"code":1,"msg":"发送失败"});          
                }
              });
            },
            error: function(error) {
              res.send({"code":1,"msg":"请求失败"});
            }
        })        
    	})     
    },
    error: function(error) {
      res.send({"code":1,"msg":"失败"});
    }
  });
}

//获取所有违规人员
function getMisMember(req,res){
	if (!req.AV.user) {
    res.redirect('/admin');
  }
  var query = new AV.Query(models.MLUser);
  query.equalTo("status",3);
  query.limit(1000);
  query.descending("createdAt"); 
  query.find({
    success:function(users) {
      var data = { "username": req.session.username, "users": users};
      res.render('admin/mistake/mistakeMember', data);
    },
    error: function(error) {
      res.render('admin/mistake/mistakeMember', {"username": req.session.username});
    }
  });
}

exports.passview = passview;
exports.alertReply = alertReply;
exports.alertReplyById = alertReplyById;
exports.getWaitingView = getWaitingView;
exports.getReView = getReView;
exports.disableUser = disableUser;
exports.disableUserWithId = disableUserWithId;
exports.resumeUser = resumeUser;
exports.resumeUserWithId = resumeUserWithId;
exports.getMisMember = getMisMember;